package com.webserver.core;

import com.webserver.http.HttpServletRequest;

import java.io.*;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;


    public ClientHandler(Socket socket) {
        this.socket = socket;


    }
    public void run(){
        try {

            //1.解析请求
            HttpServletRequest request = new HttpServletRequest(socket);

            //2.处理请求
            String path = request.getUri();

            //3.发送响应
            //映射去取址
            File rootDir = new File(
                    ClientHandler.class.getClassLoader().
                            getResource(".").toURI()
            );

            File staticDir = new File(rootDir,"static");
            File file = new File(staticDir,path);
            System.out.println("资源是否存在："+file.exists());
//            System.out.println(file);

            //3.1发送状态行
            println("HTTP/1.1 200 OK");

            //3.2发送响应头
            println("Content-Type: text/html");
            println("Content-length: " + file.length());
            println("");

            //将文件的所有字节作为正文内容发送给浏览器
            FileInputStream fis = new FileInputStream(file);
            OutputStream out = socket.getOutputStream();
            byte[] buf = new byte[1024*10];
            int len;
            while ((len = fis.read(buf)) != -1){
                out.write(buf,0,len);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        //使用给定的 charset 将此 String 编码到 byte 序列，并将结果存储到新的 byte 数组。
        out.write(data);
        out.write(13);
        out.write(10);

    }


}
